// 引入mysql的配置文件
const db = require('../../db.config');

// 引入sequelize对象
const Sequelize = db.sequelize;

// 引入数据表模型
const cosmeticsDetail = Sequelize.import('../../schema/base/cosmeticsDetail.js');
cosmeticsDetail.sync({force: false}); // 自动创建表

class CosmeticsDetailModule {
  /**
   * 新增化妆品
   */
  static async addCosmeticsDetail(data) {
    cosmeticsDetail.create(data)
  }

  /**
   * 脚本用-获取信息
   */
  static async getDetail(where, limit, rand) {
    let sql = limit ? {
      raw: true,
      where,
      limit
    } : {
      raw: true,
      where
    }
    if (rand) sql.order = [Sequelize.literal('rand()')]
    // if (rand) sql.order = 'random()'
    return await cosmeticsDetail.findAll(sql)
  }
  
  /**
   * 获取化妆品信息列表
   */
  static async getCosmeticsDetail(where, total, pagination) {
    let sql = (total && pagination) ? {
      where,
      raw: true,
      limit: +total,
      offset: total * (pagination - 1)
    } : {
      where,
      raw: true
    }
    return cosmeticsDetail.findAll(sql)
  }

  /**
   * 获取单个化妆品信息
  */
  static async getCosmeticsDetailItem(where) {
    return await cosmeticsDetail.findOne({
      where,
      raw: true
    })
  }

  /**
   * 数据更新
   */
  static async updateClassify(where, classify, des) {
    let list = await cosmeticsDetail.findOne({
      where
    })

    list.classify = classify
    list.des = des
    await list.save()
  }

  /**
   * 管理员更新数据
   */
  static async update(where, data) {
    let list = await cosmeticsDetail.findOne({
      where
    })

    data.title && (list.title = data.title)
    data.price && (list.price = data.price)
    data.picture && (list.picture = data.picture)
    data.link && (list.link = data.link)
    await list.save()
  }

  /**
   * 删除化妆品条目
   */
  static async deleteDetail(where) {
    await cosmeticsDetail.destroy({
      where
    })
  }
}

module.exports = CosmeticsDetailModule
